package Engine;

import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import Engine.util.JdbcConnection;

public class Guilds {
	
	public static void main (String args[]) {
		try {
		Connection conn = new JdbcConnection().getConnection();
		Guilds guild = new Guilds();
		guild.updateGuilds(conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private ArrayList guilds = new ArrayList();

	public Guilds newInstance() throws Exception {
		Connection conn = new JdbcConnection().getConnection();
		ResultSet rs = conn.prepareStatement(
				"Select distinct guild from wow_data.guild_list where updatetime < " +
				" ( current_timestamp -  interval 1 day) and  realm in  " +
				" (select realm from wow_data.realm_list ) limit 1000 ") 
				.executeQuery();
		while (rs.next()) {
			guilds.add(rs.getString(1));
		}
		conn.close();
		return this;
	}
	public void logGuildRun(Connection conn, String guild, String realm) throws Exception {
		PreparedStatement pst = conn.prepareStatement("update wow_data.guild_list set updatetime = current_timestamp  where guild = ? ");
		pst.setString(1, guild);
		//pst.setString(2, realm);
		pst.executeUpdate();

	}

	public void saveGuild(String guild, String realm) throws Exception {
		Connection conn = new JdbcConnection().getConnection();
		PreparedStatement pst = conn
				.prepareStatement("insert into wow_data.guild_list (guild, realm, updatetime ) values ( ?, ?, ? ) ");
		System.out.println("Saveing: " + guild);
		pst.setString(1, guild);
		pst.setString(2, realm);
		pst.setTimestamp(3, new java.sql.Timestamp( new java.util.Date().getTime() - 100000000));
		pst.executeUpdate();

		conn.close();
	}

	public void updateGuilds(Connection conn) throws SQLException {
		String guildquery = "select distinct  p.guild, p.realm from wow_data.player_list p "; 
		
		ResultSet rs = conn.prepareStatement(guildquery)
				.executeQuery();
		
		PreparedStatement pst = conn
		.prepareStatement("insert into wow_data.guild_list (guild, realm, updatetime) values ( ?, ?, ? ) ");
		while (rs.next()) {
                        guilds.add(rs.getString(1));
			pst.setString(1, rs.getString(1));
			pst.setString(2, rs.getString(2));
			pst.setTimestamp(3, new java.sql.Timestamp(new java.util.Date().getTime() - 186400000));
			try { pst.executeUpdate(); } catch (SQLException e) { //ignore 
		}}
		
	}
	public void refreshGuilds(Connection conn) {
		try {
			Character toon = new Character();
			Realms realms = new Realms().newInstance();
			ArrayList realmlist = realms.getRealms();
			Guilds guilds = new Guilds().newInstance();
			ArrayList guildlist = guilds.getGuilds();

			URL armory;
			URLConnection uconn;

			Document doc = null;
			NodeList guild;
			Node fstNode;
			Element el;

			for (int i = 0; i < guildlist.size(); i++) {
				System.out.println("Running Guild: " + guildlist.get(i));
				for (int j = 0; j < realmlist.size(); j++) {
					Thread.sleep(300);
					System.out.println("	Running Realm: " + realmlist.get(j));
					logGuildRun(conn, (String)guildlist.get(i), (String)realmlist.get(j));
					armory = new URL(
							"http://www.wowarmory.com/guild-info.xml?r="
									+ realmlist.get(j) + "&gn="
									+ guildlist.get(i));

					uconn = armory.openConnection();
					uconn.setRequestProperty("User-Agent",
							"Mozilla/4.0 (compatible; MSIE 6.0; ");
					try {
						doc = DocumentBuilderFactory.newInstance()
								.newDocumentBuilder()
								.parse(new InputSource(uconn.getInputStream()));
					} catch (Exception e) {
						if (e.getMessage().contains("500 for URL:"))
							continue;
					}
					/*
					 * if(doc == null) continue;
					 */
					doc.getDocumentElement().normalize();

					guild = doc.getElementsByTagName("character");
					for (int k = 0; k < guild.getLength(); k++) {
						fstNode = guild.item(k);
						el = (Element) fstNode;
						toon = new Character(el);
						toon.setRealm((String) realmlist.get(j));
						toon.setGuild((String) guildlist.get(i));
						try {
							toon.saveCharacter(conn);

						} catch (SQLException e) {

							if (e.getMessage().contains("Duplicate entry")) {
								toon.updateCharacter(conn);
								continue;
							}
							throw (e);
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public ArrayList getGuilds() {
		return guilds;
	}
}
